<template>
	<view>
		<view v-if="wxad_switch">
			<view @click="limit_throttle">
				<image style="width: 750rpx;margin: -120rpx 0;" src="@/pages_sub/static/wxad1.png" mode="aspectFit">
				</image>
			</view>
			<!-- <view style="color: #FFFFFF;margin-top: 18rpx;">今天已观看{{list.length}}次广告(每天最多{{maxlimit}}次)</view> -->

			<!-- 				<view class="bannerads">
				<u-line-progress :percentage="jindu" activeColor="#9370DB"></u-line-progress>
				<view style="height: 20rpx;"></view>
			</view> -->

			<view style="height: 40rpx;"></view>
			<view v-if="list.length>0" class="jilu" v-for="(item,index) in list" :key="index">
				<view>看广告获得{{item.reward_num||0}}金豆</view>
				<view>记录时间：{{$u.timeFormat(item._add_time, 'yyyy/mm/dd hh:MM:ss')}}</view>
			</view>

			<view v-if="list.length==0" class="jilu">
				<view>今天还没有领取过广告奖励哦</view>
				<view>点击页面上方【观看广告】即可开始</view>
			</view>
		</view>

		<view v-else>
			<u-empty mode="page" icon="http://cdn.uviewui.com/uview/empty/page.png" text="活动尚未开启">
			</u-empty>
		</view>

		<!-- 规则图片弹窗开始 -->
		<u-popup :round="10" mode="bottom" :show="showrule" bgColor="transparent" @close="close" :closeable="true">
			<view>
				<image style="width: 750rpx;" :src="rule_image" mode="aspectFit">
				</image>
			</view>
		</u-popup>
		<!-- 规则图片弹窗结束 -->
		<view @click="clickrule">
			<u-loadmore :status="status" :loading-text="loadingText" :loadmore-text="loadmoreText"
				:nomore-text="nomoreText" />
		</view>

	</view>
</template>


<script>
	const db = uniCloud.database();
	const _ = db.command;
	let rewardedVideoAd = null;

	export default {
		data() {
			return {
				//底部线条区
				status: 'loadmore',
				loadingText: '努力加载中',
				loadmoreText: '查看规则',
				nomoreText: '实在没有了',

				showrule: false,
				wxad_switch: vk.vuex.get('$app.appinfo.wxad_switch'), //广告开关
				wxad_id: vk.vuex.get('$app.appinfo.wxad_adid'), //广告ID
				maxlimit: vk.vuex.get('$app.appinfo.wxad_maxlimit'), //每人每天最多领取几次
				reward_num: vk.vuex.get('$app.appinfo.wxad_reward'), //每次奖励多少金豆
				rule_image: vk.vuex.get('$app.appinfo.wxad_rule'), //每次奖励多少金豆
				list: [],
				jindu: 10,

			}
		},
		onLoad() {
			if (!vk.vuex.get('$user.userInfo._id')) {
				uni.switchTab({
					url: "/pages/Tabbar/my/my"
				})
				return;
			}
			this.wxads()
		},
		onShow() {
			this.getlist()
		},
		methods: {
			getlist() {
				let todayStart = vk.vuex.get('$app.time.todayStart')
				vk.callFunction({
					url: 'client/user/kh/wxads/get_adreward_list',
					loading: false, //静默
					data: {
						todayStart: todayStart
					},
					success: (res) => {
						this.list = [];
						this.list = res.list.data;
						this.jindu = vk.pubfn.toDecimal(res.list.data.length / this.maxlimit * 100, 0);
					}
				});
			},

			wxads() {
				rewardedVideoAd = wx.createRewardedVideoAd({
					adUnitId: this.wxad_id
				})
				rewardedVideoAd.onLoad(() => {
					console.log('激励视频 广告加载成功')
				})
				rewardedVideoAd.onError((err) => {
					console.log('onError event emit', err)
					vk.alert('广告加载失败');
				})
				rewardedVideoAd.onClose((res) => {
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束，可以下发游戏奖励
						console.log("播放结束，可发放奖励");
						this.look_ads_end()
					} else {
						console.log("中途结束");
						// 播放中途退出，不下发游戏奖励
					}
				})
			},

			limit_throttle() {
				//节流操作，3秒内只响应一次
				vk.pubfn.throttle(() => {
					this.showad()
				}, 2000);
			},

			async showad() {
				console.log("展示广告了");
				vk.showLoading('加载中...');
				//========先检查今日广告有没有超标========
				let todayStart = vk.vuex.get('$app.time.todayStart')
				let adcount = await db.collection('a_wxads').where({
					_add_time: _.gt(todayStart),
					user_id: vk.vuex.get('$user.userInfo._id'),
					type: "wxads"
				}).get()
				vk.hideLoading();
				if (adcount.result.data.length > this.maxlimit - 1) {
					vk.alert('今日已达标，请明天再来吧');
					return;
				}
				//========检查结束========
				// 重新拉取新广告
				rewardedVideoAd.load()
					.then(() => {
						// 用户触发广告后，显示激励视频广告
						rewardedVideoAd.show().catch(() => {
							// 失败重试
							rewardedVideoAd.load()
								.then(() => rewardedVideoAd.show())
								.catch(err => {
									console.log('激励视频 广告显示失败')
								})
						})
					})
					.catch(err => {
						console.log('激励视频 广告拉取失败', err)
					})
			},

			//观看广告完成，获取奖励
			look_ads_end() {
				//节流操作，3秒内只响应一次
				vk.pubfn.throttle(() => {
					vk.callFunction({
						url: 'client/user/kh/wxads/wxads_reward',
						title: '请求中...',
						data: {
							reward_num: this.reward_num,
							wxad_id: this.wxad_id, //广告位ID
							maxlimit: this.maxlimit,
							todayStart: vk.vuex.get('$app.time.todayStart')
						},
						success: (data) => {
							console.log("data=", data);
							if (data.tips) {
								vk.alert(data.tips);
							} else {
								uni.showToast({
									title: "奖励已发放!",
									icon: "success"
								})
								this.getlist()
							}
						}
					});
				}, 3000);

			},

			clickrule() {
				this.showrule = !this.showrule
			},
			close() {
				console.log("规则弹窗关闭");
				this.showrule = false;
			},
		}
	}
</script>

<style>
	.bannerads {
		margin: 0 10rpx;
		width: 98%;
		position: fixed;
		bottom: 50rpx;
	}

	page {
		background-color: #ffffff;
	}



	.jilu {
		background-color: #E6E6FA;
		color: #000000;
		margin: 20rpx;
		padding: 20rpx;
		border-radius: 20rpx;
		font-size: 28rpx;
	}
</style>